<?php

class SubjectController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */
        $this->list_sess_unset('controller_subject');
        $this->session_search_key = 'controller_subject';
        $this->session_search_name = 'search_label';


        if ($this->_getParam('subj_id') && $this->_getParam('subj_id') != "") {
            $subj_id = $this->_getParam('subj_id');
            $subjectModel = new Model_Subject();
            $subjectdata = $subjectModel->fetchEntryByViewId($subj_id, $this->USER->usr_lang_id);
            if ($this->USER->role != 'ADMIN') {
                if ($subjectdata['com_id'] != $this->USER->company_id) {
                    $this->_helper->redirector('list', 'subject', '');
                }
            }
        }
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'subject', '');
    }

    public function viewAction() {
        if ($this->_getParam('subj_id') && $this->_getParam('subj_id') != "") {
            $subj_id = $this->_getParam('subj_id');
        } else {
            $this->_helper->redirector('list', 'subject', '');
        }
        $subjectModel = new Model_Subject();
        $subjectdata = $subjectModel->fetchEntryByViewId($subj_id, $this->USER->usr_lang_id);
        $updated_id = $subjectdata['lgn_id'];
        /* get user name which is updated data* */
        $loginModel = new Model_Login();
        $updated_by_user = $loginModel->getUserData(Array('lgn_id' => $updated_id));
        $user_name = ucfirst($updated_by_user->name) . " [" . ucfirst($updated_by_user->role) . "]";

        $this->view->admindata = $user_name;
        $this->view->subjectdata = $subjectdata;
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "";
        $searchtype = "";
        $orderField = 'subj_id';
        $sort = 'asc';
        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }

        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;

        //PAGING_PER_PAGE

        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }
        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }
        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }
        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;
        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = $this->ZFTRANSLATE->translate("select_one_checkbox");
                }
            }
            /* Search Facility Over Here */
            if ($postedData["searchtype"] == "") {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
            }
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                $where = "subj_name LIKE '%$searchtype%' OR dep_name LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
                $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            }
        } else {
            $searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            $where = "subj_name LIKE '%$searchtype%' OR dep_name LIKE '%$searchtype%'  ";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
            $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
        }

        if ($this->USER->roletype == 'Contractor' || $this->USER->roletype == 'SuperContractor' ||
                $this->USER->roletype == 'Customer' || $this->USER->roletype == 'SuperCustomer') {
            $where .=' ) AND (site.com_id=' . $this->USER->company_id;
        } else {
            $where .='';
        }

        $subjectModel = new Model_Subject();
        $subjectsData = $subjectModel->fetchSubject($where, $itemsPerPageReviews, $offset, $orderField, $sort);
        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($subjectModel->getSubjectCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'subject', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        $this->view->paginator = $paginator;
        $this->view->subjectsData = $subjectsData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $subjectModel->getStatusArray();
        $this->view->searchtype = $searchtype;
    }

    public function deleteAction($ids = Array()) {
        //Load Subject Model 
        $subjectModel = new Model_Subject();
        if ($this->_getParam('subj_id') && $this->_getParam('subj_id') != "") {
            $subject_id = $this->_getParam('subj_id');
            $subjectModel->deleteSubject($subject_id);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("subj_delete_success"));
            $this->_helper->redirector('list', 'subject', '');
        } else {
            $subjectModel->deleteSubject($ids);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("subj_delete_success"));
            $this->_helper->redirector('list', 'subject', '');
        }
    }

    public function formAction() {

        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $subjectData = Array();
        $this->view->mode = "Add";

        //Load login Model
        $loginModel = new Model_Login();

        //Load Subject Model
        $subjectModel = new Model_Subject();

        //Load Subject Form
        $subjectForm = new Form_SubjectForm();


        $imageName = "";

        $CustContData = $loginModel->fetchCustomerContratcor();


        //Load the site array for the select box in form 
        $siteArray = $subjectModel->getsiteArray();
        $subjectForm->site_id->addMultiOptions($siteArray);


        //Load the department array for the select box in form 
        $departmentArray = $subjectModel->getdepartmentArray();
        $subjectForm->dep_id->addMultiOptions($departmentArray);

        //Load the status array for the select box in form 
        $statusArray = $subjectModel->getStatusArray();
        $subjectForm->subj_status->addMultiOptions($statusArray);

        //Load the quality array for the select box in form 
        $typeArray = $subjectModel->gettypeArray($this->USER->usr_lang_id);
        $subjectForm->type_id->addMultiOptions($typeArray);


        //Check for the subject Parameter
        $subjectData['subj_id'] = $this->_request->getParam('subj_id');
        $subj_id = (!empty($subjectData['subj_id'])) ? $subjectData['subj_id'] : null;


        $calloutModel = new Model_Callout();
        $calloutData = $calloutModel->fetchCallout("call.subj_id = '" . $subj_id . "'");


        if (!empty($subj_id)) {
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $subjectModel->fetchEntryById($subj_id);
            $imageName = $data['subj_instruction'];
            $departmentArray = $subjectModel->getdepartmentArray("department.site_id = '" . $data['site_id'] . "'");
            $subjectForm->dep_id->addMultiOptions($departmentArray);
        }



        //Populate form 
        $this->view->form = $subjectForm->populate($data);
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            //Check for Errors
            //Image Validation

            if ($postedData['site_id'] != '') {
                //     echo 'in';exit;
                $departmentArray = $subjectModel->getdepartmentArray("department.site_id = '" . $postedData['site_id'] . "'");
                $subjectForm->dep_id->addMultiOptions($departmentArray);
            }


            /* if ($_FILES['subj_instruction']['name'] != '') {
              $gtlObj = new GTL_Common();
              $imageAllowedFormat = $gtlObj->allowedImageFormats();
              $responseText = $gtlObj->image_validate($imageAllowedFormat, 'subj_instruction');
              if ($responseText == 'IMPROPER_FORMAT') {
              $errorMessageArray[] = $this->ZFTRANSLATE->translate("contractor_required_image"); #'Please upload image with valid file format.';
              }
              } */
            if ($this->view->mode == "Add") {
                /* if ($_FILES['subj_instruction']['name'] != '') {
                  $gtlObj = new GTL_Common();
                  $imageAllowedFormat = $gtlObj->allowedImageFormats();
                  $responseText = $gtlObj->image_validate($imageAllowedFormat, 'subj_instruction');
                  if ($responseText == 'IMPROPER_FORMAT') {
                  $errorMessageArray[] = $this->ZFTRANSLATE->translate("contractor_required_image"); #'Please upload image with valid file format.';
                  }
                  } */
            }


            if (!$subjectForm->isValid($postedData)) {
                $errorMessage = $subjectForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {

                if (count($errorMessageArray) > 0) {
                    
                } else {
                    if ($this->view->mode == "Add") {
                        $SubjectCount = $subjectModel->getSubjectCount('');
                        $subjectData['subj_createddate'] = date("Y-m-d H:i:s");
                    }

                    //Image upload
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    foreach ($upload->getFileInfo() as $fields => $asFileInfo) {
                        if ($asFileInfo['name'] != '') {
                            $folder = $this->config->UPLOAD_PATH . "subject/";
                            $upload->setDestination($folder);
                            $originalFilename = pathinfo($asFileInfo['name']);
                            $fileName = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                            $upload->addFilter('Rename', $fileName, 'filename');
                            $upload->receive($fields);
                            $subjectData['subj_instruction'] = $fileName;
                        }
                    }


                    /* authentication login id */

                    $updated_userid = $this->USER->lgn_id;
                    //Subject save
                    $subjectData['updated_lgn_id'] = $updated_userid;
                    $subjectData['subj_id'] = $subj_id;
                    $subjectData['dep_id'] = $postedData['dep_id'];
                    $subjectData['site_id'] = $postedData['site_id'];
                    $subjectData['type_id'] = $postedData['type_id'];
                    $subjectData['subj_name'] = $postedData['subj_name'];
                    $subjectData['subj_delay'] = $postedData['subj_delay'];
                    $subjectData['subj_status'] = $postedData['subj_status'];
                    $subjectData['subj_updateddate'] = date("Y-m-d H:i:s");
                    $subjectModel->save($subjectData, 'subj_id');
                    if ($this->view->mode == "Add") {
                        $successmessage = $this->ZFTRANSLATE->translate("subj_add_success");
                    } else {
                        $successmessage = $this->ZFTRANSLATE->translate("subj_update_success");
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'subject', '');
                }
            }
        }
        $this->view->CustContData = $CustContData;
        $this->view->calloutData = $calloutData;
        $this->view->mode = $this->view->mode;
        $this->view->subjectid = $subj_id;
        $this->view->imageName = $imageName;
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $subjectForm;
    }

    public function departmentlistAction() {
        $listString = "";
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
            $subjectModel = new Model_Subject();
            $site_id = $postedData['site_id'];
            $departmentWhere = "department.site_id = '" . $site_id . "'";
            //Load the customer array for the select box in form 
            $departmentArray = $subjectModel->getdepartmentArray($departmentWhere);
            $jsonString = "";
            $jsonString = "<select name='dep_id' id='dep_id'>";
            foreach ($departmentArray as $key => $_dep) {
                //print_r($_cust);
                $jsonString .= "<option value = '" . $key . "'>" . $_dep . "</option>";
            }
            $jsonString .= "</select>";
        }
        echo $jsonString;
        exit;
    }

    public function calloutAction() {
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $requestData = Array();
        $this->view->mode = "Add";
        $subj_where = '';


        //Load callout Model
        $calloutModel = new Model_Callout();

        //Load callout Form
        // $calloutForm = new Form_CalloutForm();
        $callData = array();

        //Load the status array for the select box in form 
        $statusArray = $calloutModel->getStatusArray();
        // $calloutForm->call_status->addMultiOptions($statusArray);


        $callData['call_id'] = $this->_request->getParam('call_id');
        $call_id = (!empty($requestData['call_id'])) ? $requestData['call_id'] : null;

        $callData['subj_id'] = $this->_request->getParam('subj_id');
        $subj_id = (!empty($requestData['subj_id'])) ? $requestData['subj_id'] : null;


        if (!empty($req_id)) {
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $calloutModel->fetchEntryById($call_id);
        }


        //Populate form 
        //$requestForm->req_date->setValue('date');
        //$this->view->form = $calloutForm->populate($data);

        if ($this->getRequest()->isPost()) {
            //Check for Errors
            if ($this->view->mode == "Add") {
                
            }
            $postedData = $this->_request->getPost();


            if (count($errorMessageArray) > 0) {
                
            } else {
                if ($this->view->mode == "Add") {
                    //   $CalloutCount = $calloutModel->getCalloutCount('');
                    $callData['call_createddate'] = date("Y-m-d H:i:s");
                }
                $callData['call_person'] = $postedData['call_person'];
                $callData['call_contact_no'] = $postedData['call_contact_no'];
                $callData['call_comment'] = $postedData['call_comment'];
                $callData['call_status'] = 1;
                $callData['call_updateddate'] = date("Y-m-d H:i:s");
                $calloutModel->save($callData, 'call_id');

                if ($this->view->mode == "Add") {
                    $successmessage = $this->ZFTRANSLATE->translate("call_add_success");
                } else {
                    $successmessage = $this->ZFTRANSLATE->translate("call_update_success");
                }

                $subj_id = $this->_request->getParam('subj_id');
                $this->addSuccessMessage($successmessage);
                $this->_helper->redirector('form', 'subject', null, array('subj_id' => $subj_id));
            }
        }
        $this->view->mode = $this->view->mode;
        $this->view->requestid = $req_id;
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        // $this->view->form = $calloutForm;
    }

    public function deletecalloutAction() {
        $calloutModel = new Model_Callout();
        if ($this->_getParam('call_id') && $this->_getParam('call_id') != "") {
            $call_id = $this->_getParam('call_id');
            $subj_id = $this->_getParam('subj_id');
            $calloutModel->deleteCallout($call_id);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("call_delete_success"));
            $this->_helper->redirector('form', 'subject', null, array('subj_id' => $subj_id));
        }
    }

}

?>
